<template>
	<view class="content">
		<privacyPopup></privacyPopup>
		<uni-search-bar class="searchbar" radius="5" @confirm="doSearch" @clear="doClear" v-model="blueName"
			clearButton="auto" cancelButton="none" placeholder="请输入蓝牙名称">
		</uni-search-bar>
		<!-- <view class="header">
			<text>蓝牙模块</text>
		</view> -->
		<view class="blue-list">
			<!-- ,{'isActive':item.isActive} -->
			<view v-for="(item, index) in searchList" :key="index" @click.prevent="goEquipInfo(item)"
				:class="['cards']">
				<view class="item-left">
					<view class="names">{{item.localName || item.name}}
						<!-- <text class="isconnect" v-if="item.isActive">已连接</text> -->
					</view>
					<view class="service">{{item.advertisServiceUUIDs&& item.advertisServiceUUIDs.length || 0}}
						Service Advertised</view>
					<view class="device">
						{{item.deviceId}}
					</view>
				</view>
				<view class="item-right">
					<image class="signal" :src="'/static/image/'+signalUrl(item)" mode="widthFix"></image>
					<view class="dbm">{{item.RSSI}}dBm</view>
				</view>
			</view>
			<view class="cards empty-content" v-if="searchList.length==0">
				<u-empty></u-empty>
			</view>
		</view>
		<tabBar :current="0"></tabBar>
	</view>
</template>

<script>
	import tabBar from "@/components/tabBar.vue";
	import {
		mapState,
	} from 'vuex';
	import {
		users
	} from '@/api/api.js';

	import privacyPopup from "@/components/privacyPopup.vue";
	import {
		checkBluetoothStatus
	} from "@/utils/index.js";
	export default {
		components: {
			tabBar: tabBar,
			privacyPopup,
		},
		data() {
			return {
				devicesList: [ // 测试数据
					{
						localName: "CHZD12DPC0231017001",
						deviceId: "99999994243546546567768787989809---8787989809",
						RSSI: "-50"
					},
					{
						localName: "CC12DPC0231017001",
						deviceId: "99999994243546546567768787989809---8787989809",
						RSSI: "-50"
					},
				],
				blueName: "", //蓝牙name
				searchList: [
					// 测试数据
					{
						localName: "CHZD12DPC0231017001",
						deviceId: "99999994243546546567768787989809---8787989809",
						RSSI: "-50"
					},
					{
						localName: "CC12DPC0231017001",
						deviceId: "99999994243546546567768787989809---8787989809",
						RSSI: "-50"
					},
				],
				refresh: false, //下拉刷新标识
			}
		},
		computed: {
			...mapState(['isOpenBle', 'curConnectBLE']),
		},
		watch: {
			// 监听蓝牙设备
			'$store.state.devicesList': {
				immediate: true,
				deep: true,
				async handler(e) {
					if (this.refresh) {
						uni.stopPullDownRefresh();
						this.refresh = false;
					}
					if (e.length > 0) {
						this.devicesList = e;
						this.doSearch();
					}
				}
			},
			'$store.state.curConnectBLE': {
				immediate: true,
				deep: true,
				handler(e) {
					console.log(e)
					this.searchList.forEach(item => item.isActive = false);
					console.log('当前已连接设备=========')
					console.log(this.curConnectBLE)
					// 如果蓝牙列表没有已连接设备,则将已连接设备push到列表
					if (this.curConnectBLE.length > 0) {
						let index = this.searchList.findIndex(p => p.deviceId == this.curConnectBLE[0].deviceId);
						if (index != -1) {
							this.searchList[index].isActive = true;
						} else {
							this.searchList = [...this.curConnectBLE, ...this.searchList];
						}
					}
				},
			}
		},
		onLoad(e) {
			checkBluetoothStatus();
			this.$store.dispatch('startBluetoothDevicesDiscovery')
				.then(res => {
					console.log(res)
				})
				.catch(err => {})
			this.blueName = e.blueName ?? "";
			this.doSearch();
		},
		// 监测已连接蓝牙设备
		async onShow() {
			// 未登录,则跳转登录页
			let token = uni.getStorageSync('token') || null;
			if (!token) {
				uni.reLaunch({
					url: '/pages/login/index'
				});
				return;
			}
			this.checkToken();
			
			let {
				serviceId,
			} = require('@/utils/service.js');
			if (this.devicesList.length > 0 && this.isOpenBle) {
				// 测试数据 services: '0000180F-0000-1000-8000-00805F9B34FB'
				let data = await this.$store.dispatch('getConnectedBluetoothDevices', {
					services: serviceId
				});
			}
		},
		methods: {
			async goEquipInfo(item) {
				let deviceType = "";
				if ((item.localName && item.localName.startsWith('CC')) || (item.name && item.name.startsWith('CC'))) {
					deviceType = "CC";
				} else if ((item.localName && item.localName.startsWith('CHZD')) || (item.name && item.name.startsWith(
						'CHZD'))) {
					deviceType = "CHZD";
				}
				
				// 测试
				uni.navigateTo({
					url: `/pagesA/bluetooth/index?deviceInfo=${encodeURIComponent(JSON.stringify(item))}`
				})
				return;
				
				if (deviceType == 'CC' || deviceType == 'CHZD') {
					uni.navigateTo({
						url: `/pagesA/bluetooth/index?deviceInfo=${encodeURIComponent(JSON.stringify(item))}`
					})
				} else {
					this.$Toast.none('设备类型不匹配~');
				}
			},
			// 搜索
			doSearch() {
				this.searchList = [];
				this.devicesList.forEach((item, index) => {
					if ((item.localName && item.localName.toLowerCase().indexOf(this.blueName) != -1) || (item
							.name && item.name.toLowerCase().indexOf(this.blueName) != -1)) { // 判断是否含有匹配的值;
						this.searchList.push(item);
					}
				});
				let index = -1;
				this.searchList.forEach(item => item.isActive = false);
				this.curConnectBLE.map((
					item) => {
					index = this.searchList.findIndex(p => p.deviceId == item.deviceId);
					if (index != -1) {
						this.searchList[index].isActive = true;
					}
				});
			},
			doClear() {
				this.blueName = "";
				this.doSearch();
			},
			onPullDownRefresh() {
				this.refresh = true;
				this.$store.dispatch('startBluetoothDevicesDiscovery');
			},
			rssiToPercentage(rssi) {
				const minRSSI = -100; // 最小信号强度值
				const maxRSSI = -40; // 最大信号强度值
				const percentage = (rssi - minRSSI) / (maxRSSI - minRSSI) * 100;
				return Math.max(0, Math.min(percentage.toFixed(1), 100)); // 限制百分比在 0 到 100 之间
			},
			signalUrl(item) {
				let quality = Math.min(Math.max(2 * (item.RSSI + 100), 0), 100)
				return 'signal' + Math.round(quality / 25) + '.png'
			},
			// 登录心跳检测
			checkToken() {
				users('/heartbeat', 'get').then(res => {});
			},
		}
	}
</script>
<style>
	page {
		background-color: #EFF0F1 !important;
	}
</style>
<style lang="scss" scoped>
	@import "@/static/css/common.scss";

	.content {
		.header {
			background: linear-gradient(45deg, #0081ff, #1cbbb4);
			height: 500rpx;
			text-align: center;
			color: #ffffff;

			text {
				line-height: 340rpx;
				font-size: 72rpx;
				font-weight: 900;
				letter-spacing: 8px;
				filter: drop-shadow(2px 8px 1px black);
			}
		}

		.titles {
			font-size: 40rpx;
			color: #000000;
			font-weight: bold;
			margin-bottom: 50rpx;
		}

		.blue-list {
			position: relative;
			top: -20rpx;
			padding-bottom: 160rpx;

			.cards {
				@include flexLayout(center, space-between);
				@include cards;
				flex-direction: row;
				border-bottom: 2rpx solid #efefef;

				.item-left {
					width: 85%;
					word-break: break-all;

					.names {
						font-size: 42rpx;
						color: #033C7B;
						font-weight: bold;
					}

					.service {
						font-size: 24rpx;
						color: #9A9A9A;
						margin: 20rpx 0;
					}

					.device {
						font-size: 26rpx;
						color: #9A9A9A;
					}
				}

				.item-right {
					text-align: center;

					image {
						width: 50rpx;
					}

					.dbm {
						color: #1cbbb4;
					}
				}
			}

			.isActive {
				background-color: #d2f9f7;
				color: #ffffff;
			}

			.isconnect {
				color: #1cbbb4;
				font-size: 28rpx;
				margin-left: 20rpx;
			}

			.empty-content {
				height: 80vh;
				justify-content: center;
			}
		}
	}
</style>